<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="8" :offset="7">
        <el-form label-width="250px">
          <el-form-item v-for="(c, index) in config" v-bind:key="index" :label="$t(`config.${c.Key}`)">
            <el-input v-if="c.Kind === 0" v-model="config[index].Value"></el-input>
            <el-switch v-if="c.Kind === 1" v-model="config[index].Value"></el-switch>
            <el-select v-if="c.Kind === 2" v-model="config[index].Value" placeholder="">
              <el-option
                  v-for="(item, index) in c.Options.split('|')"
                  :key="index"
                  :label="item"
                  :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveConfig">{{ $t('config.save') }}</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getCurrentInstance } from 'vue';
import utils from '@/utils.js'
const that = getCurrentInstance()

const config = ref([])

onMounted(() => {
    getAllConfig()
  })

function getAllConfig() {
      utils.GET('/manager/configs').then(res => {
        Object.assign(config.value, res)
        for (let i = 0; i < config.value.length; i++) {
          // Convert the string to boolean
          if (config.value[i].Kind === 1) {
            config.value[i].Value = config.value[i].Value === 'true'
          }
        }
      }).catch(err => proxy.$message.error(err))
    }
function saveConfig() {
      for (let i = 0; i < config.value.length; i++) {
        // Convert the boolean to string
        if (config.value[i].Kind === 1) {
          config.value[i].Value = config.value[i].Value.toString()
        }
      }
      utils.PUT('/manager/config', config.value).then(res => {
        proxy.$message.success(res)
        getAllConfig()
        // Hard code here, the index 5 is the `default_language`.
        //this.$i18n.locale = this.config[5].Value
      }).catch(err => proxy.$message.error(err))
    }
</script>

<style scoped>

</style>